import socket

client = socket.socket()
client.connect(("localhost", 8080))
while True:
    cmd = input(">>:").strip()
    if len(cmd)==0: continue
    if cmd.startswith("get"):
        client.send(cmd.encode())  # 发送请求
        server_response = client.recv(1024)
        if server_response.decode().startswith("not"):
            print("请输入有效文件名")
            continue
        client.send(b"ready to recv file")  # 发送确认
        file_size = int(server_response.decode())  # 获取文件大小
        rece_size=0
        filename = cmd.split()[1]
        f = open(filename + ".new", "wb")
        while rece_size < file_size:
            if file_size - rece_size > 1024:  # 要收不止一次
                size = 1024
            else:  # 最后一次了，剩多少收多少,防止之后发送数据粘包
                size = file_size - rece_size
                print("last receive:", size)
            recv_data = client.recv(size)
            rece_size += len(recv_data)  # 累加接受数据大小
            f.write(recv_data)  # 写入文件,即下载
        else:
            print("文件下载完成")
            f.close()
client.close()


